define(function (require, exports, module) {

'use strict';

var $ = require('$'),
    Confirm = require('confirm'),
    Tips = require('tips'),
    Tabs = require('tabs'),
    Select = require('select'),
    Locker = require('locker');

var Setting = require('../magickimg/setting'),
    Process = require('../magickimg/process'),
    Button = require('../upload/base/button');

var Upload = require('./upload/core'),
    Browse = require('./browse/browse');

/**
 * 弹窗图片库
 *
 * @module common/image/dialog
 * @class  Dialog
 * @constructor
 * @extends Confirm
 * @return {[type]}   [description]
 */
var Dialog = Confirm.extend({

  defaults: {
    classPrefix: 'ue-dialog ue-dialog-tabs',
    content: require('./dialog.tpl'),
    css: {
      position: 'absolute',
      width: 930
    },
    events: {
      'before:destroy': function () {
        // 阻止Confirm的关闭后自动销毁
        return false;
      },
      'render': function () {
        this.initTabs();
      },
      'submit': function () {
        this.processPic(this.browse.getSelectedData());
        return false;
      }
    },
    // 图片列表配置
    galleryOptions: {
      formCfg: {
        // buttons: [{
        //   colspan: null,
        //   'class': 'pull-right',
        //   value: '<i class="fa fa-plus"></i> 上传水印',
        //   attrs: {
        //     type: 'button',
        //     'data-role': 'add'
        //   }
        // }],
        data: {
          groups: [{
            colspan: null,
            attrs: {
              type: 'select',
              name: 'userUploaded'
            },
            options: [{
              value: 'true',
              text: '我上传的',
              selected: true
            }, {
              value: 'false',
              text: '全部'
            }]
          }, {
            // label: '图片名称',
            colspan: null,
            attrs: {
              type: 'text',
              name: 'name',
              size: 11,
              maxlength: 20,
              placeholder: '图片名称'
            }
          }, {
            colspan: null,
            attrs: {
              type: 'select',
              name: 'type'
            },
            options: [{
              value: '1',
              text: '宽',
              selected: true
            }, {
              value: '2',
              text: '高'
            }]
          }, {
            colspan: null,
            attrs: {
              type: 'text',
              name: 'min',
              size: 3,
              maxlength: 4,
              digits: 'digits',
              min: 0,
              max: 3000,
              placeholder: '最小'
            }
          }, {
            colspan: null,
            value: '-',
            attrs: {
              type: 'static'
            }
          }, {
            colspan: null,
            attrs: {
              type: 'text',
              name: 'max',
              size: 3,
              maxlength: 4,
              digits: 'digits',
              min: 0,
              max: 3000,
              placeholder: '最大'
            }
          }, {
            colspan: null,
            value: '<i class="fa fa-search"></i> 搜索',
            attrs: {
              type: 'submit'
            }
          }]
        }
      },
      buttons: null,
      keepHistory: false,
      key: {
        title: 'name',
        url: 'remotePath',
        id: 'fid'
      },
      thumbAffix: '!a-1-160x120.jpg',
      // element: '#J_GallerySearch',
      pageSize: 10,
      selectable: 'single',
      url: 'imageSearch',
      delegates: {
        'change [name=min]': function (e) {
          var target = e.currentTarget,
              value = +target.value,
              maxValue = +target.form.elements.max.value;
          if (maxValue && value > maxValue) {
            target.value = maxValue;
          }
        },
        'change [name=max]': function (e) {
          var target = e.currentTarget,
              value = +target.value,
              minValue = +target.form.elements.min.value;
          if (minValue && value < minValue) {
            target.value = minValue;
          }
        }
      }
    },
    initialTab: 0,
    needDimens: false,
    title: '<ul class="nav nav-tabs" data-role="tabs">' +
        '<li class="active"><a href="#gallery-dialog-browse" data-role="tab">图片库</a></li>' +
        '<li><a href="#gallery-dialog-upload" data-role="tab">上传</a></li>' +
      '</ul>',
    uploadOptions: {
    }
  },

  initTabs: function () {
    var self = this;

    self.tabs = new Tabs({
      element: self.element,
      initialTab: self.option('initialTab'),
      events: {
        tab: function (e, tab, pane) {
          self['init' + tab[0].hash.split('-')[2].replace(/^[a-z]/, function (a) {
            return a.toUpperCase();
          })](pane);
        }
      }
    });
  },

  initUpload: function (pane) {
    var self = this,
        options;

    self.activeTab = 1;
    self.role('foot').hide();

    if (self.upload) {
      return;
    }

    options = self.option('uploadOptions');

    $.extend(true, options, {
      container: pane,
      events: {
        complete: function (e, queueFile, settings) {
          self.processPic([queueFile.data()], true, settings);
        },
        error: function (e, msg) {
          new Tips({
            content: msg
          });
        }
      },
      hasLink: self.option('hasLink')
    });

    self.upload = new Upload(options);

    this.initUploadButton(pane);
  },

  initUploadButton: function (pane) {
    var self = this;

    self.button = new Button({
      container: pane,
      data: {
        icon: 'times',
        label: '关闭窗口'
      },
      delegates: {
        'click': function () {
          self.close();
        }
      },
      disabled: false
    });
  },

  initBrowse: function (pane) {
    var self = this,
        options;

    self.activeTab = 0;
    self.role('foot').show();

    if (self.browse) {
      return;
    }

    options = self.option('galleryOptions');

    $.extend(true, options, {
      element: pane,
      events: {
        diselect: function (e, data) {
          self.hideSetting(data);
        },
        select: function (e, data) {
          self.showSetting(data);
        },
        load: function (e) {
          self.hideSetting();
        }
      }
    });

    self.browse = new Browse(options);

    self.initSelects();
    self.initSetting();
  },

  initSelects: function () {
    var self = this;

    new Select({
      field: self.browse.$('[name=userUploaded]'),
      events: {
        change: function () {
          self.browse.form.submit();
          // self.browse.refresh();
        }
      }
    });

    new Select({
      field: self.browse.$('[name=type]')
    });
  },

  initSetting: function () {
    this.settingLocker = new Locker();
  },

  showSetting: function (data) {
    var self = this,
        locker = self.settingLocker,
        setting = locker.get(data.id),
        settings, p;

    if (!setting) {
      setting = new Setting({
        classPrefix: 'gallery-setting',
        container: self.browse.element,
        data: data,
        filterData: data,
        hasLink: self.option('hasLink'),
        readonly: true
      });

      locker.set(data.id, setting);
    }

    setting.show();

    settings = locker.get();
    for (p in settings) {
      if (settings[p] !== setting) {
        settings[p].hide();
      }
    }
  },

  hideSetting: function (data) {
    var self = this,
        locker = self.settingLocker,
        setting,
        settings, p;

    if (data) {
      setting = locker.get(data.id);
      if (setting) {
        setting.hide();
        return;
      }
    } else {
      settings = locker.get();
      for (p in settings) {
        if (settings[p].is(':visible')) {
          settings[p].hide();
        }
      }
    }
  },

  switchTab: function (name) {
    this.tabs.slide(typeof name === 'number' ? name : (name === 'upload') ? 1 : 0);
    this.show();
    this.focus();
  },

  /**
   * 图片处理
   *
   * @return {[type]} [description]
   */
  processPic: function (datas, processed, settings) {
    var self = this,
        i = 0, len = 0;

    function loadImage (data, callback, settings) {
      var tries = 0, maxTries = 10, cals;

      function cal (data, toData) {
        var width = data.width,
            height = data.height;

        if (!!toData.width) {
          height = toData.width * height / width;
          width = toData.width;
        }

        return {
          width: width,
          height: height
        };
      }

      function fire (data, width, height) {
        self.fire('processPic', {
          remotePath: data.remotePath,
          thumbUrl: data.thumbUrl,
          width: width || data.width,
          height: height || data.height,
          remark: data.remark,
          linkOriginal: data.linkOriginal
        });
      }

      function go () {
        var image = new Image();

        image.onload = function () {
          self.currentPicUrl = data.thumbUrl;
          fire(data, this.width, this.height);

          if (++i === len) {
            if (callback) {
              callback.call(self);
            }
          }
        };

        image.onerror = function () {
          if (tries++ < maxTries) {
            go();
          } else {
            // 多次尝试，还是取不到真是尺寸
            cals = cal(data, settings);
            fire(data, cals.width, cals.height);
            // new Tips({
            //   content: '图片读取失败，请检查'
            // });
            if (++i === len) {
              if (callback) {
                callback.call(self);
              }
            }
          }
        };

        image.src = data.thumbUrl;
      }

      if (self.option('needDimens')) {
        go();
      } else {
        fire(data);
        if (callback) {
          callback.call(self);
        }
      }
    }

    if (!datas || !datas.length) {
      new Tips({
        content: '请选择图片'
      });
      return;
    }

    len = datas.length;

    // 从上传口过来
    if (processed) {
      settings || (settings = {});
      datas.forEach(function (data) {
        data.linkOriginal = settings.linkOriginal;
        loadImage(data, function () {
          self.fire('complete');
        }, settings);
      });
    } else {
      // 从图库选择口过来
      datas.forEach(function (data) {
        var setting = self.settingLocker.get(data.id);

        settings = setting ? setting.get() : {};

        // 魔图
        new Process({
          imageUrl: data.remotePath,
          settings: settings,
          events: {
            complete: function (e, thumbUrl) {
              data.thumbUrl = thumbUrl;
              data.linkOriginal = settings.linkOriginal;
              loadImage(data, function () {
                self.close();
              }, settings);
            },
            error: function (e, msg) {
              new Tips({
                content: msg
              });
            }
          }
        });
      });
    }
  }

});

module.exports = Dialog;

});
